package com.xinting.piano.service;

import android.util.Log;
import android.util.SparseArray;

import com.xinting.piano.data.PApp;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wuxinting on 15/11/23.
 * 广播消息
 */
public class PBroadcast {

    public static final String LOG_TAG = PApp.LOG_TAG+"_broadcast";

    private SparseArray<List<IListener>> listeners;
    private static PBroadcast broadcast;

    private PBroadcast() {
        listeners = new SparseArray<>();
    }

    public static PBroadcast getInstance() {
        if (broadcast == null) {
            synchronized (PBroadcast.class) {
                if (broadcast == null) {
                    broadcast = new PBroadcast();
                }
            }
        }
        return broadcast;
    }

    /**
     * 注册监听
     * @param id 要监听的广播ID
     * @param listener
     */
    public void register(int id, IListener listener) {
        Log.d(LOG_TAG, "Broadcast register " + id);
        List<IListener> iListenerList = listeners.get(id, null);
        if (iListenerList == null) {
            iListenerList = new ArrayList<>();
            listeners.append(id, iListenerList);
        }

        iListenerList.add(listener);
    }

    /**
     * 注销监听
     * @param id 要注销的监听ID，等同于监听的广播ID
     */
    public void unRegister(int id, IListener listener) {
        List<IListener> iListenerList = listeners.get(id, null);
        if (iListenerList == null) {
            return;
        }

        iListenerList.remove(listener);
    }

    /**
     * 广播
     * @param id 广播的ID
     * @param data 广播附带的数据
     */
    public void broadcast(int id, Object data) {
        Log.d(LOG_TAG, "Broadcast broadcast " + id);
        List<IListener> iListenerList = listeners.get(id, null);
        if (iListenerList == null) {
            return;
        }

        for (IListener listener : iListenerList) {
            listener.listen(data);
        }
    }

    /**
     * 监听者接口
     */
    public interface IListener {
        void listen(Object data);
    }

}
